<script setup>
import { ref, reactive, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  getEmailCaptcha,
  getImgCaptcha,
} from "@/utils/api/Captcha.js";
import { signinNewUser } from "@/utils/api/User.js";

const router = useRouter();

const formRef = ref(null); // 获取表单实例
const formData = ref({
  userEmail: "",
  userPhoneNum: "",
  userName: "",
  userCompany: "",
  userPassword: "",
  confirmPassword: "",
  userEmailCaptcha: "",
  invitationToken: "",
});

const validatePasswordMatch = (rule, value, callback) => {
  if (value !== formData.value.userPassword) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const rules = reactive({
  userEmail: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
    },
  ],
  userPhoneNum: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userCompany: [{ required: true, message: "请输入工作单位", trigger: "blur" }],
  userPassword: [{ required: true, message: "请输入密码", trigger: "blur" }],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePasswordMatch, trigger: "blur" },
  ],
  userEmailCaptcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
  ],
});

let imgCaptchaBase64 = ref("失败链接");
let imgCaptchaValue = ref(""); // 后端返回的验证码
let showNonRobotVerify = ref(false);
let userImgCaptchaVal = ref("");
let timer = null;
const totalSec = 60;
let currentSec = ref(60);
let isCounting = ref(false); // 防止重复点击验证码按钮

function register() {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    else {
        console.log(formData.value)
        const {confirmPassword, ...registerInfo} = formData.value;
      const registerRes = await signinNewUser(registerInfo);
      if (registerRes) {
        ElMessage.success("注册成功，即将返回登陆页面！");
        setTimeout(() => {
          router.push("/login");
        }, 3000);
      } else {
        ElMessage.error("注册失败，请稍后重试！");
      }
    }
  });
}

async function onBeforeClose() {
  showNonRobotVerify.value = false;
}

// 发送验证码
function gainEmailCaptcha() {
  if (isCounting.value) {
    ElMessage.warning("请稍后再试");
    return;
  } else {
    formRef.value.validateField("userEmail", (valid) => {
      if (!valid) {
        ElMessage.error("请输入正确的邮箱");
      } else {
        console.log(formData.value.userEmail);
        startCountdown();
        getEmailCaptcha(formData.value.userEmail)
          .then((response) => {
            // 请求成功的处理
            console.log("邮件发送成功:", response);
            ElMessage.success("邮件发送成功");
          })
          .catch((error) => {
            // 请求失败的处理
            console.error("邮件发送失败:", error);
            ElMessage.error("邮件发送失败");
          });
      }
    });
  }
}

// 倒计时逻辑
function startCountdown() {
  isCounting.value = true;
  timer = setInterval(() => {
    currentSec.value--;
    if (currentSec.value <= 0) {
      clearInterval(timer);
      currentSec.value = totalSec;
      isCounting.value = false;
    }
  }, 1000);
}

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <div class="container">
    <h1>会议中心注册</h1>

    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="邮箱账号:" prop="userEmail">
        <el-input
          v-model="formData.userEmail"
          placeholder="请输入邮箱"
        ></el-input>
      </el-form-item>

      <el-form-item label="手机号码:" prop="userPhoneNum">
        <el-input v-model="formData.userPhoneNum" placeholder="请输入手机号">
          <template #prepend>中国+86</template>
        </el-input>
      </el-form-item>

      <el-form-item label="姓名:" prop="userName">
        <el-input
          v-model="formData.userName"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>

      <el-form-item label="工作单位:" prop="userCompany">
        <el-input
          v-model="formData.userCompany"
          placeholder="请输入工作单位"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码:" prop="userPassword">
        <el-input
          v-model="formData.userPassword"
          type="password"
          placeholder="请输入密码"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item label="确认密码:" prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item label="邀请码:">
        <el-input
          v-model="formData.invitationToken"
          placeholder="邀请码（非必填）"
          show-password
        ></el-input>
      </el-form-item>


      <el-form-item label="验证码:" prop="userEmailCaptcha">
        <el-input
          v-model="formData.userEmailCaptcha"
          placeholder="请输入验证码"
        >
          <template #append>
            <el-button
              :type="isCounting ? 'success' : 'primary'"
              @click="gainEmailCaptcha"
              :disabled="isCounting"
            >
              {{ isCounting ? `重新获取(${currentSec})` : "获取验证码" }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <!-- 注册 按钮 -->
    <div class="btn-group">
      <el-button type="success" @click="register">注册</el-button>
    </div>
  </div>
</template>

<style scoped>
.container {
  max-width: 400px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 20px;
  background: white;
  border: 1px solid #512a10;
  border-radius: 12px;
}

h1 {
  text-align: center;
  font-size: 18px;
  margin-bottom: 10px;
}

.btn-group {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 15px;
}

.btn-group .el-button {
  width: 200px;
}
</style>
